package com.dabai.addtofavorites;

import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.util.Linkify;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemLongClickListener;
import com.dabai.addtofavorites.adapter.FavAdapter;
import com.dabai.addtofavorites.bean.FavData;
import com.dabai.addtofavorites.databinding.ActivityMainBinding;
import com.dabai.addtofavorites.ui.MyCollectionActivity;
import com.dabai.addtofavorites.utils.FavFileUtils;
import com.dabai.dbutils.data.Patterns;
import com.dabai.dbutils.dialog.MdcDialog;
import com.dabai.dbutils.qrcode.QRCodeUtils;
import com.dabai.dbutils.toast.DBToast;
import com.dabai.dbutils.utils.DabaiUtils;
import com.dabai.dbutils.utils.FileUtils;
import com.dabai.dbutils.utils.RemindUtils;
import com.dabai.dbutils.utils.ShareUtils;
import com.dabai.dbutils.utils.StringUtils;
import com.dabai.dbutils.utils.component.ActivityUtils;
import com.dabai.uitools.utils.DisplayUtils;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.permissionx.guolindev.PermissionX;
import com.yanzhenjie.recyclerview.OnItemMenuClickListener;
import com.yanzhenjie.recyclerview.SwipeMenu;
import com.yanzhenjie.recyclerview.SwipeMenuBridge;
import com.yanzhenjie.recyclerview.SwipeMenuCreator;
import com.yanzhenjie.recyclerview.SwipeMenuItem;
import com.yanzhenjie.recyclerview.SwipeRecyclerView;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Matcher;

public class MainActivity extends AppCompatActivity {

    ActivityMainBinding amb;
    Context context;

    FavAdapter favAdapter;
    LinearLayoutManager linearLayoutManager;

    StaggeredGridLayoutManager staggeredGridLayoutManager;
    private String link;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        amb = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(amb.getRoot());

        context = this;


        linearLayoutManager = new LinearLayoutManager(context);
        staggeredGridLayoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
        amb.recyclerView.setLayoutManager(staggeredGridLayoutManager);
        // amb.recyclerView.addItemDecoration(new DividerItemDecoration(context, LinearLayout.VERTICAL));

        // 创建侧滑 和 设置侧滑监听器  一定要在 adapter设置之前!!!
        amb.recyclerView.setSwipeMenuCreator(mSwipeMenuCreator);
        amb.recyclerView.setOnItemMenuClickListener(mItemMenuClickListener);

        //设置adapter
        refData();

        registerToMonitorEvents();

    }


    // 创建菜单：
    SwipeMenuCreator mSwipeMenuCreator = new SwipeMenuCreator() {
        @Override
        public void onCreateMenu(SwipeMenu leftMenu, SwipeMenu rightMenu, int position) {

            SwipeMenuItem item1 = new SwipeMenuItem(context)
                    .setHeight(MATCH_PARENT)
                    .setWidth(DisplayUtils.dip2px(context, 70))
                    .setText("追加")
                    .setBackgroundColor(Color.parseColor("#3F51B5"))
                    .setTextColor(Color.WHITE);
            rightMenu.addMenuItem(item1); // 在Item左侧添加一个菜单。


            SwipeMenuItem item2 = new SwipeMenuItem(context)
                    .setHeight(MATCH_PARENT)
                    .setWidth(DisplayUtils.dip2px(context, 70))
                    .setText("删除")
                    .setBackgroundColor(Color.parseColor("#F44336"))
                    .setTextColor(Color.WHITE);
            rightMenu.addMenuItem(item2); // 在Item左侧添加一个菜单。

        }
    };

    // 菜单点击监听。
    OnItemMenuClickListener mItemMenuClickListener = (menuBridge, position) -> {
        // 任何操作必须先关闭菜单，否则可能出现Item菜单打开状态错乱。
        menuBridge.closeMenu();

        // 左侧还是右侧菜单：
        int direction = menuBridge.getDirection();
        // 菜单在Item中的Position：
        int menuPosition = menuBridge.getPosition();

        //判断是 右侧菜单
        if (direction == SwipeRecyclerView.RIGHT_DIRECTION) {
            if (menuPosition == 0) {

                if (StringUtils.isEmpty(DabaiUtils.getClipboardContent(context))) {
                    DabaiUtils.showToast(context, "追加失败:空内容!");
                    return;
                }

                MdcDialog.showInputDialog(this, "添加附加信息", "", "附加信息", new MdcDialog.OnInputDialogButtonListener() {
                    @Override
                    public void confirm(AlertDialog dialog, String content) {

                        if (content.isEmpty()){
                            return;
                        }

                        FavData favData = favAdapter.getData().get(position);
                        FileUtils.writeText(favData.getFile()
                                , FileUtils.readText(favData.getFile())
                                        +"\n("+content+")");
                        refData();
                        DabaiUtils.showToast(context, "追加成功!");

                        dialog.dismiss();
                    }

                    @Override
                    public void cancel() {

                    }
                }).getWindow().setWindowAnimations(R.style.DBAnim_Transitions_Via);

                
            }
            if (menuPosition == 1) {

                FavData favData = favAdapter.getData().get(position);
                FileUtils.delete(favData.getFile().getAbsolutePath());
                favAdapter.remove(favData);
                DabaiUtils.showToast(context, "删除成功!");

            }
        }
    };


    private void refData() {

        ArrayList<FavData> arrayList = (ArrayList<FavData>) FavFileUtils.getAllFile(context);
        favAdapter = new FavAdapter(arrayList);
        amb.recyclerView.setAdapter(favAdapter);

        registerToMonitorEvents();

        amb.swipeRefreshLayout.setRefreshing(false);

        staggeredGridLayoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
        amb.recyclerView.setLayoutManager(staggeredGridLayoutManager);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == 401) {
                if (data != null) {

                    String socLink = QRCodeUtils.getQrCodeScannerResult(data);

                    Matcher matcher = Patterns.WEB_URL.matcher(socLink);
                    if (matcher.find()) {
                        link = matcher.group();

                        MdcDialog.showConfirmDialog(context, "提示"
                                , "是否获取网站标题?", new MdcDialog.OnConfirmDialogButtonListener() {
                                    @Override
                                    public void confirm() {
                                        new Thread(() -> {

                                            try {

                                                Document doc = Jsoup.connect(link).get();

                                                runOnUiThread(() -> {
                                                    releaseText(doc.title() + "\n" + socLink);
                                                    DBToast.showText(context, "获取标题成功!", true);
                                                });

                                            } catch (IOException e) {
                                                runOnUiThread(() -> {
                                                    releaseText(socLink);
                                                    DBToast.showText(context, "获取标题失败!", false);
                                                });
                                            }
                                        }).start();

                                    }

                                    @Override
                                    public void cancel() {
                                        releaseText(socLink);
                                    }
                                });
                    }

                }
            }
        }

    }

    /**
     * 注册监听事件
     */
    @SuppressLint("UseCompatLoadingForDrawables")
    private void registerToMonitorEvents() {


        amb.swipeRefreshLayout.setOnRefreshListener(this::refData);
        amb.swipeRefreshLayout.setColorSchemeColors(getResources().getColor(R.color.purple_500));


        amb.scanButton.setOnClickListener(v -> {

            QRCodeUtils.startQrCodeScanner(this, 401);

        });

        amb.releaseButton.setOnClickListener(v -> {

            MdcDialog.showInputDialog(context, "手动添加", "", "请输入要分享的内容", new MdcDialog.OnInputDialogButtonListener() {
                @Override
                public void confirm(AlertDialog dialog, String content) {
                    if (!content.isEmpty()){

                        releaseText(content);
                        dialog.dismiss();
                    }
                }
                @Override
                public void cancel() {

                }
            }).getWindow().setWindowAnimations(com.dabai.uitools.R.style.DBAnim_Transitions_Via);

        });


        favAdapter.setOnItemClickListener((adapter, view, position) -> {
            FavData favData = favAdapter.getData().get(position);
            String content = FileUtils.readText(favData.getFile());

            new MaterialAlertDialogBuilder(context)
                    .setTitle("内容")
                    .setMessage(content)
                    .setNegativeButton("复制", (dialog, which) -> {

                        DabaiUtils.copyText(context, content);

                    })
                    .setPositiveButton("分享", (dialog, which) -> {

                        ShareUtils.shareText(context, content);

                    }).setNeutralButton("取消", null)
                    .show().getWindow().setWindowAnimations(com.dabai.uitools.R.style.DBAnim_Transitions_Via);

        });

        favAdapter.setOnItemLongClickListener((adapter, view, position) -> {
            FavData favData = favAdapter.getData().get(position);
            String content = FileUtils.readText(favData.getFile());

            Matcher matcher = Patterns.WEB_URL.matcher(content);
            if (matcher.find()) {
                DabaiUtils.openLinkWithBrowserActivity(context, matcher.group());
            } else {
                DBToast.showYellowToast(context, "未检测到链接!");
            }
            return true;
        });

    }


    /**
     * 发布到本地仓库和列表
     *
     * @param text 内容
     */
    public void releaseText(String text) {
        if (StringUtils.isEmpty(text)) {
            DabaiUtils.showToast(context, "收藏失败!");
            return;
        }

        FavData favData = new FavData();
        favData.setContent(text);

        if (FavFileUtils.createFile(context, favData)) {
            refData();
            DabaiUtils.showToast(context, "收藏成功!");
        } else {
            DabaiUtils.showToast(context, "收藏失败!");
        }

    }


    //菜单
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main, menu);
        return super.onCreateOptionsMenu(menu);
    }


    StringBuilder stringBuilder;

    @SuppressLint("NonConstantResourceId")
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.myContent:
                ActivityUtils.startActivity(context, MyCollectionActivity.class);
                break;
            case R.id.copyContent:

                if (favAdapter.getData().isEmpty()) {
                    DabaiUtils.showToast(context, "无内容!");
                    return true;
                }

                stringBuilder = new StringBuilder();
                for (FavData content : favAdapter.getData()) {
                    stringBuilder.append(content.getContent() + "\n\n");
                }

                String text = stringBuilder.substring(0, stringBuilder.length() - 2);
                DabaiUtils.copyText(context, text);

                break;
            case R.id.shareContent:

                if (favAdapter.getData().isEmpty()) {
                    DabaiUtils.showToast(context, "无内容!");
                    return true;
                }

                stringBuilder = new StringBuilder();
                for (FavData content : favAdapter.getData()) {
                    stringBuilder.append(content.getContent()).append("\n\n");
                }

                String text2 = stringBuilder.substring(0, stringBuilder.length() - 2);
                ShareUtils.shareText(context, text2);

                break;
            case R.id.clearContent:
                MdcDialog.showConfirmDialog(context, "提示", "确定清空分享集合吗?", new MdcDialog.OnConfirmDialogButtonListener() {
                    @Override
                    public void confirm() {
                        FavFileUtils.delAll(context);
                        refData();
                    }

                    @Override
                    public void cancel() {

                    }
                }).getWindow().setWindowAnimations(com.dabai.uitools.R.style.DBAnim_Transitions_Via);
                break;
            case R.id.remind:


                PermissionX.init(this)
                        .permissions(Manifest.permission.READ_CALENDAR, Manifest.permission.WRITE_CALENDAR)
                        .request((allGranted, grantedList, deniedList) -> {
                            if (!allGranted) {
                                DBToast.showText(context, "无日历权限，不能使用此功能。", false);
                            } else {
                                Calendar cal = Calendar.getInstance();
                                //日期加1
                                cal.add(Calendar.DAY_OF_YEAR, 1);
                                //时间设定到8点整
                                cal.set(Calendar.HOUR_OF_DAY, 9);
                                cal.set(Calendar.SECOND, 0);
                                cal.set(Calendar.MINUTE, 0);
                                cal.set(Calendar.MILLISECOND, 0);

                                boolean isOk = RemindUtils.addCalendarEvent(context, "记得分享\"收藏夹内容\"给好友", "分享内容给好友", cal.getTimeInMillis(), 0);
                                DBToast.showMethodsFeedbackText(context, isOk, "添加提醒成功!", "添加提醒失败!");
                            }
                        });


                break;
        }
        return super.onOptionsItemSelected(item);
    }


    // 用来计算返回键的点击间隔时间
    private long exitTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                //弹出提示，可以有多种方式
                Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                finish();
            }
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }

}